package com.itheima.utils;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.itheima.entity.SmsResponse;


/**
 * @outhor
 * @date 2020/2/5 10:54
 */

public class SmsUtil {
    public static SmsResponse sendSmsCode(String phoneNumber,String code ){
        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou",
                "LTAI4Fnbh2tYkQ9njWzyVuLy",  //阿里云KeyId
                "bshiiGskIa9kmJU2hJPiQ5SVB9Z72U"); //阿里云secret
        IAcsClient client = new DefaultAcsClient(profile);

        CommonRequest request = new CommonRequest();
        request.setMethod(MethodType.POST);
        request.setDomain("dysmsapi.aliyuncs.com");
        request.setVersion("2017-05-25");
        request.setAction("SendSms");
        request.putQueryParameter("RegionId", "cn-hangzhou");
        request.putQueryParameter("PhoneNumbers", phoneNumber);
        request.putQueryParameter("SignName", "传智健康");//阿里云的签名
        request.putQueryParameter("TemplateCode", "SMS_183185078");//阿里云的模板
        JSONObject parameter = new JSONObject();
        parameter.put("code",code);
        request.putQueryParameter("TemplateParam", parameter.toJSONString());
        try {
            CommonResponse response = client.getCommonResponse(request);
            System.out.println(response.getData());
            //反馈数据可封装为对象进行返回
            SmsResponse smsResponse = JSONObject.parseObject(response.getData(), SmsResponse.class);
            return smsResponse;
            //{"Message":"OK","RequestId":"06792680-0531-4223-BA51-26FE284ECEDF","BizId":"946319180872838620^0","Code":"OK"}
        } catch (ServerException e) {
            //如有超时可在这里处理
            e.printStackTrace();
        } catch (ClientException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void main(String[] args) {
        SmsResponse smsResponse = sendSmsCode("18616867866", "0000");
        System.out.println("smsResponse = " + smsResponse);
    }
}